<?php


namespace app\index\controller;
use app\common\controller\Frontend;
use think\Db;
use think\facade\Config;
use think\facade\Cookie;
use think\facade\Hook;
use think\facade\Env;
use Overtrue\Pinyin\Pinyin;

class App extends Frontend
{
    protected $layout = 'default';
    protected $noNeedLogin = [''];
    protected $noNeedRight = ['*'];

    public function initialize()
    {
        parent::initialize();
        $auth = $this->auth;

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

        //监听注册登录注销的事件
        Hook::add('user_login_successed', function ($user) use ($auth) {
            $expire = input('post.keeplogin') ? 30 * 86400 : 0;
            Cookie::set('uid', $user->id, $expire);
            Cookie::set('token', $auth->getToken(), $expire);
        });
        Hook::add('user_register_successed', function ($user) use ($auth) {
            Cookie::set('uid', $user->id);
            Cookie::set('token', $auth->getToken());
        });
        Hook::add('user_delete_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');
        });
        Hook::add('user_logout_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');
        });
    }

    /**
     * 空的请求
     * @param $name
     * @return mixed
     */
    public function _empty($name)
    {
        $data = Hook::listen("user_request_empty", $name);
        foreach ($data as $index => $datum) {
            $this->view->assign($datum);
        }
        return $this->view->fetch('app/' . $name);
    }

    /**
     * 应用中心
     */
    public function app()
    {

        $this->view->assign('title','我的应用');
        $uid = $this->auth->id;
        $list =  Db::name('app')->where([['user_id','=',$uid],['status','=','normal']])->order('id desc')->select();
        $this->view->assign('appList', $list);
        return $this->view->fetch();
    }

    public function add()
    {
        $this->view->engine->layout(false);
        $this->view->assign('title','新增应用');
        return $this->view->fetch();
    }

    public function save()
    {
        $post = $this->request->post();
        $have =  Db::name('app')->where([['title','=',$post['title']]])->field('id')->find();
        if(!empty($have))
        {
            $this->error('名称重复,请换个名称','',$post);
        }
        $uid = $this->auth->id;
        $app_id = strtolower('wx'.encrypt(strtolower($post['letter']).$uid,'E',strtolower($post['letter'])));
        $app_secret = base64_encode($app_id);
        $data = [
            'title'=>$post['title'],
            'desc'=>$post['desc'],
            'letter'=>strtolower($post['letter']),
            'status'=>'normal',
            'app_id'=>$app_id,
            'app_secret'=>$app_secret,
            'create_time'=>date('Y-m-d H:i:s'),
            'user_id'=>$uid,
        ];
        $id =  Db::name('app')->insertGetId($data);
        $this->success('success','',$data);
    }

    public function live()
    {
        $id = $this->request->param('id',0);
        if($id == 0)
        {
            $this->error('非法操作');
        }
        $uid = $this->auth->id;
        $app = Db::name('app')->where([['user_id','=',$uid],['id','=',$id]])->find();
        if(!empty($app))
        {
            $this->view->assign('title',$app['title'].'('.$app['app_name'].')');
            $this->view->assign('app', $app);

            $list =  Db::name('live')->where([['user_id','=',$uid],['status','=','normal']])->order('id desc')->select();
            if(!empty($list))
            {
                $timeStamp = Env::get('liveserver.timestamp');

                $push_key = Env::get('liveserver.push_key');

                $play_key = Env::get('liveserver.play_key');
                foreach ($list as $k=>$v)
                {
                    //推流key -- app_id -- live_id -- user_id
                    $push_key_str = $push_key.'-'.$v['app_id'].'-'.$v['id'].'-'.$v['user_id'];
                    $publish_auth_key = '/'.$app['app_name'].'/'.$v['stream'].'-'.$timeStamp.'-0-0-'.$push_key_str;
                    $push_auth_key = encrypt($publish_auth_key,'E',Env::get('liveserver.encrypt_key'));
                    $list[$k]['publish_auth_key'] = $push_auth_key;
                    //拉流key -- app_id -- live_id -- user_id
                    $play_key_str = $play_key.'-'.$v['app_id'].'-'.$v['id'].'-'.$v['user_id'];
                    $plays_auth_key = '/'.$app['app_name'].'/'.$v['stream'].'-'.$timeStamp.'-0-0-'.$play_key_str;
                    $play_auth_key = encrypt($plays_auth_key,'E',Env::get('liveserver.encrypt_key'));
                    $list[$k]['play_auth_key'] = $play_auth_key;
                }
            }
            $this->view->assign('liveList', $list);
            return $this->view->fetch();
        }
        else
        {
            $this->error('无对应的应用');
        }
    }

    public function live_add()
    {
        $this->view->engine->layout(false);
        $id = $this->request->param('id',0);
        $uid = $this->auth->id;
        $app = Db::name('app')->where([['user_id','=',$uid],['id','=',$id]])->find();
        $this->view->assign('app', $app);
        //TD($id);
        $this->view->assign('title','新增应用');
        return $this->view->fetch();
    }

    public function live_save()
    {
        $post = $this->request->post();
        $uid = $this->auth->id;
        if(empty($post['title']))
        {
            $this->error('名称必须');
        }
        $have =  Db::name('live')->where([['app_id','=',$post['app_id']],['user_id','=',$uid],['title','=',$post['title']]])->field('id')->find();
        if(!empty($have))
        {
            $this->error('名称重复,请换个名称','',$post);
        }
        $app =  Db::name('app')->where([['id','=',$post['app_id']]])->find();
        $pinyin = new Pinyin();
        $text = $post['title'];
        $initials = $pinyin->abbr($text); // 获取首字母缩写
        $stream = $initials;
        $data = [
            'title'=>$post['title'],
            'stream'=>$stream,
            'app_id'=>$post['app_id'],
            'user_id'=>$uid,
            'status'=>'normal',
            'live_status'=>'0',
            'create_time'=>date('Y-m-d H:i:s'),
            'publish_url'=>'rtmp://'.Env::get('liveserver.ip').'/'.$app['app_name'].'/'.$stream,
            'rtmp_play_url'=>'rtmp://'.Env::get('liveserver.ip').'/'.$app['app_name'].'/'.$stream,
            'flv_play_url'=>'http://'.Env::get('liveserver.ip').':'.Env::get('liveserver.httpport').'/'.$app['app_name'].'/'.$stream.'.live.flv',
            'hls_play_url'=>'http://'.Env::get('liveserver.ip').':'.Env::get('liveserver.httpport').'/'.$app['app_name'].'/'.$stream.'/hls.m3u8',
            'webrtc_play_url'=>'http://'.Env::get('liveserver.ip').':'.Env::get('liveserver.httpport').'/index/api/webrtc?app='.$app['app_name'].'&stream='.$stream.'&type=play',
        ];
        $id =  Db::name('live')->insertGetId($data);
        $this->success('success','',$data);
    }

    public function live_url()
    {
        $this->view->engine->layout(false);
        $this->view->assign('title','查看推流/拉流地址');

        $id = $this->request->param('id',0);
        $uid = $this->auth->id;
        $live = Db::name('live')->where([['user_id','=',$uid],['id','=',$id]])->find();
        if(!empty($live))
        {
            $app = Db::name('app')->where([['id','=',$live['app_id']]])->find();
            $timeStamp = Env::get('liveserver.timestamp');

            $push_key = Env::get('liveserver.push_key');

            $play_key = Env::get('liveserver.play_key');

            //推流key -- app_id -- live_id -- user_id
            $push_key_str = $push_key.'-'.$live['app_id'].'-'.$live['id'].'-'.$live['user_id'];
            $publish_auth_key = '/'.$app['app_name'].'/'.$live['stream'].'-'.$timeStamp.'-0-0-'.$push_key_str;
            $push_auth_key = encrypt($publish_auth_key,'E',Env::get('liveserver.encrypt_key'));
            $live['publish_auth_key'] = $push_auth_key;
            //拉流key -- app_id -- live_id -- user_id
            $play_key_str = $play_key.'-'.$live['app_id'].'-'.$live['id'].'-'.$live['user_id'];
            $plays_auth_key = '/'.$app['app_name'].'/'.$live['stream'].'-'.$timeStamp.'-0-0-'.$play_key_str;
            $play_auth_key = encrypt($plays_auth_key,'E',Env::get('liveserver.encrypt_key'));
            $live['play_auth_key'] = $play_auth_key;
        }


        $this->view->assign('live', $live);

        return $this->view->fetch();
    }
    public function live_play()
    {
        $this->view->engine->layout(false);
        $this->view->assign('title','播放');

        $id = $this->request->param('id',0);
        $uid = $this->auth->id;
        $live = Db::name('live')->where([['user_id','=',$uid],['id','=',$id]])->find();
        if(!empty($live))
        {
            $app = Db::name('app')->where([['id','=',$live['app_id']]])->find();
            $timeStamp = Env::get('liveserver.timestamp');

            $play_key = Env::get('liveserver.play_key');

            //拉流key -- app_id -- live_id -- user_id
            $play_key_str = $play_key.'-'.$live['app_id'].'-'.$live['id'].'-'.$live['user_id'];
            $plays_auth_key = '/'.$app['app_name'].'/'.$live['stream'].'-'.$timeStamp.'-0-0-'.$play_key_str;
            $play_auth_key = encrypt($plays_auth_key,'E',Env::get('liveserver.encrypt_key'));
            $live['play_auth_key'] = $play_auth_key;
        }


        $this->view->assign('live', $live);

        return $this->view->fetch();
    }

}